const connection = require('../app/database')

class PermissionService {
	async checkMoment(userId, momentId) {
		const statement = `SELECT * FROM moment WHERE user_id = ? AND id = ?`
		const [result] = await connection.execute(statement, [userId, momentId])
		return !!result.length
	}

	async checkResouce(resouceName, resouceId, userId) {
		const statement = `SELECT * FROM ${resouceName} WHERE user_id = ? AND id = ?`
		const [result] = await connection.execute(statement, [userId, resouceId])
		return !!result.length
	}
	// 判断是否是管理员
	async checkAdmin(id) {
		const statement = `SELECT * FROM users WHERE id = ? AND role_id =2`
		const [result] = await connection.execute(statement, [id])
		return !!result.length
	}

	// 判断是否是社团社长
	async checkClubLeader(id, club_id) {
		const statement = `
		SELECT role FROM club_members
		WHERE user_id = ? AND club_id = ? AND status = 'active';
	`
		const [result] = await connection.execute(statement, [id, club_id])
		if (result.length === 0) {
			return false
		} else {
			console.log(result[0])
			if (result[0].role === 'leader') {
				return true
			}
			return false
		}
	}

	// 判断这个帖子是不是他自己写
	async checkPostBelong(id, post_id) {
		const statement = `
			SELECT * FROM posts WHERE user_id = ? AND id = ?
		`
		const [result] = await connection.execute(statement, [id, post_id])
		return !!result.length
	}
}

module.exports = new PermissionService()
